﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Warehouse.DataAccess
{
    public partial class User : CustomeEntity<User>
    {
        protected override System.Linq.Expressions.Expression<Func<User, bool>> GetPredicate()
        {
            return p => p.ID == this.ID;
        }

        #region Public Static Methods
        public static User GetUser(int ID)
        {
            return GetOne(p => p.ID == ID);
        }

        public static int Login(string loginName, string password)
        {
            password = Encrypt(password);
            using (WarehouseClassesDataContext context = new WarehouseClassesDataContext())
            {
                var user = (from t in context.User where t.LoginName == loginName && t.Password == password select t).FirstOrDefault();
                if (user != null)
                {
                    return user.ID;
                }
                return -1;
            }
        }
        public static string Encrypt(string oldstring)
        {
            byte[] bytes = Encoding.Default.GetBytes(oldstring);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(bytes);
            string result = BitConverter.ToString(output).Replace("-", "");
            return result;
        }

        public static User[] GetUsers()
        {
            return GetList().ToArray();
        }

        public static User[] GetUsersByDepID(int depID)
        {
            return GetList(p => p.DepartmentID == depID).ToArray();
        }
        #endregion
    }
}
